package com.marketingexpert.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.marketingexpert.dao.AuthorityDao;
import com.marketingexpert.domain.permission.Operation;
import com.marketingexpert.domain.permission.Resource;
import com.marketingexpert.domain.permission.Role;
import com.marketingexpert.domain.permission.RolePermission;
import com.marketingexpert.domain.permission.UserRole;
import com.marketingexpert.util.WebUtils;

public class AuthorityInterceptor extends HandlerInterceptorAdapter {

	private AuthorityDao authorityDao;

	private final static String OPERATION = "use";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		String reqResource = request.getServletPath();
		if (!reqResource.startsWith("/pc")) {
			return true;
		}

		String reqOperation = OPERATION;
		// String reqResource = request.getParameter("resource");

		String parentUserId = (String) request.getSession().getAttribute(
				"parentUserId");

		UserRole ur = authorityDao.getUserRole(parentUserId);

		boolean hasPermission = false;
		Role role = authorityDao.getRole(ur.getRoleId());

		List<RolePermission> rps = authorityDao.getRolePermission(role.getId());

		for (RolePermission rp : rps) {
			com.marketingexpert.domain.permission.Permission permission = rp
					.getPermission();

			Resource resource = permission.getResource();
			Operation operation = permission.getOperation();

			if (operation.getOperationName().equals(reqOperation)
					&& resource.getUrl().equals(reqResource)) {
				hasPermission = true;
				break;
			}

		}

		if (!hasPermission) {
			response.sendRedirect(WebUtils.getBasepath(request) + "/authorityFail.jsp");
			return false;
		} else {
			return true;
		}

	}

	public AuthorityDao getAuthorityDao() {
		return authorityDao;
	}

	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}

}
